package com.szf.task.service;

import java.lang.reflect.Constructor;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;

import com.szf.base.exception.GenericException;
import com.szf.task.entity.AppInfo;
import com.szf.task.entity.Task;
import com.szf.task.service.api.AbstractApiInterface;
import com.szf.task.service.api.ApiInterface;

public class TaskManager {
	private int poolSize;
	private ThreadPoolExecutor pool;
	private Map<String, ApiInterface> taskMap;
	private AppService appService;
	private TaskService taskService;

	private List<String> weblogIds;

	public TaskManager(int poolSize) {
		this.poolSize = poolSize;
		pool = new ThreadPoolExecutor(poolSize, poolSize * 2, 60,
				TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
		taskMap = new ConcurrentHashMap<String, ApiInterface>();
	}

	@PostConstruct
	public void init() {
		weblogIds = taskService.getResultWebId();
	}

	public void addTask(Task task) {
		if (!taskMap.containsKey(task.getTaskId())) {
			try {
				Class clazz = Class.forName(task.getClassKey());
				AppInfo appInfo = appService.findById(task.getAppId());
				Constructor<AbstractApiInterface> con = clazz.getConstructor(
						Task.class, AppInfo.class);
				AbstractApiInterface api = con.newInstance(task, appInfo);
				taskMap.put(task.getTaskId(), api);
				pool.execute(api);
			} catch (Exception e) {
				throw new GenericException(e.getMessage(), e);
			}
		}

	}

	public ApiInterface getApi(String taskId) {
		return taskMap.get(taskId);
	}

	public List<String> getWeblogIds() {
		return weblogIds;
	}

	public static void main(String[] args) {
		String s = "发河a蟹表中a国人民共x产党举行我靠产人民aaaa飞币党！";
		Pattern p = Pattern
				.compile("(共(.){0,5}?产(.){0,5}?党)|(中(.){0,5}?国)|(人(.){0,5}?民(.){0,5}?币)|(假(.){0,5}?钞)|(印(.){0,5}?钞)|(法(.){0,5}?轮(.){0,5}?功)|(政(.){0,5}?府)|(游(.){0,5}?行)|(团(.){0,5}?体)|(色(.){0,5}?情)|(情(.){0,5}?色)|(主(.){0,5}?席)|(总(.){0,5}?理)|(部(.){0,5}?长)|(紫(.){0,5}?阳)|(河(.){0,5}?蟹)");

		Matcher m = p.matcher(s);

		while (m.find()) {
			System.out.println(m.group());
		}
	}

	@Autowired
	public void setAppService(AppService appService) {
		this.appService = appService;
	}

	@Autowired
	public void setTaskService(TaskService taskService) {
		this.taskService = taskService;
	}

}
